package com.example.spider.web;

import com.example.spider.cluster.msg.MsgSender;
import com.example.spider.provider.m3u8.task.M3u8TsTask;
import com.example.spider.starter.SpiderStarter;
import jakarta.servlet.http.HttpServletResponse;
import org.shoulder.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.Duration;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 触发 http://localhost:8080/spider/trigger/Why10ListResultHandler/xxx
 * 所有再跑的任务 http://localhost:8080/spider/listAll
 * 测试发消息 http://localhost:8080/spider/testSend?delayTime=2
 * 开启定时调度 http://localhost:8080/spider/enable/{xx}
 * 关闭定时调度 http://localhost:8080/spider/disable/{xx}
 * 停止任务 http://localhost:8080/spider/stop/{type}/xxx
 */
@RequestMapping("spider")
@RestController
public class SpiderController {

    @Lazy
    @Autowired(required = false)
    private Map<String, SpiderStarter> starterMap;

    @Autowired(required = false)
    private MsgSender msgSender;

    @ResponseBody
    @RequestMapping(value = "testSend", produces = "text/plain; version=0.0.4; charset=utf-8")
    public String testSend(Long delayTime) {
        if (msgSender == null) {
            return "not in cluster profile!";
        }
        M3u8TsTask t = new M3u8TsTask()
                .setIdempotentFilePath("G:\\spider\\test.ts")
                .setUrl("https://cdn-bo3.mangguo-youku.com:5278/20210606/sHkMYNjl/10000kb/hls/RZEos7kY.ts");
        msgSender.addSpiderTask(t, Duration.ofSeconds(delayTime != null ? delayTime : 0));
        return "ok";
    }

    @ResponseBody
    @RequestMapping(value = "listAll", produces = "text/plain; version=0.0.4; charset=utf-8")
    public String listAll() {
        return filterStarterAndDo("ter", s -> {
        });
    }

    @ResponseBody
    @RequestMapping(value = "trigger/{starterName}", produces = "text/plain; version=0.0.4; charset=utf-8")
    public String triggerStarter(@PathVariable("starterName") String starterName) {
        return filterStarterAndDo(starterName, SpiderStarter::startSpiders);
    }

    @ResponseBody
    @RequestMapping(value = "enable/{starterName}", produces = "text/plain; version=0.0.4; charset=utf-8")
    public String enable(@PathVariable("starterName") String starterName) {
        return filterStarterAndDo(starterName, SpiderStarter::enableCronExecute);
    }

    @ResponseBody
    @RequestMapping(value = "disable/{starterName}", produces = "text/plain; version=0.0.4; charset=utf-8")
    public String disable(@PathVariable("starterName") String starterName, HttpServletResponse response) throws IOException {
        return filterStarterAndDo(starterName, SpiderStarter::disableCronExecute);
    }

    private String filterStarterAndDo(String starterName, Consumer<SpiderStarter> consumer) {
        if (starterMap == null) {
            return "empty";
        }
        Map<String, SpiderStarter> triggered = starterMap.entrySet().stream()
                .filter(e -> StringUtils.isEmpty(starterName) || e.getKey().contains(starterName))
                .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
        if (triggered.isEmpty()) {
            return "empty";
        }
        triggered.values().forEach(consumer);
        return String.join(",", triggered.keySet());
    }
}
